package db;

import beans.Word;
import dao.WordDAO;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;

/**
 * Redis数据库操作方法封装
 */
public class RedisQuery {

    /**
     * 添加数据,相同key会覆盖数据，所以也相当于改
     */
    public static void set(String key, String value) {
        Jedis jedis = JedisDBPool.getConnectJedis();
        jedis.set(key, value);
        //Jedis3.0版本后jedisPool.returnResource(final Jedis resource)方法已被弃用，用jedis.close()代替 来归还连接
        jedis.close();
    }


    /**
     * 添加数据，带超时时间，超时自动销毁
     */
    public static void setex(String key, String value, int seconds){
        Jedis jedis = JedisDBPool.getConnectJedis();
        jedis.setex(key, seconds, value);
        jedis.close();
    }

    /**
     * 根据key删除数据
     */
    public static void deleteByKey(String key) {
        Jedis jedis = JedisDBPool.getConnectJedis();
        jedis.del(key);
        jedis.close();
    }

    /**
     * 根据key查询
     */
    public static String getByKey(String key) {
        Jedis jedis = JedisDBPool.getConnectJedis();
        String value = jedis.get(key);
        jedis.close();
        return value;
    }

    /**
     * 查询某条数据是否存在
     */
    public static boolean isExist(String key){
        Jedis jedis = JedisDBPool.getConnectJedis();
        boolean exist = jedis.exists(key);
        jedis.close();
        return exist;
    }

    public final static String DICTIONARY_PATH = "Dictionary";

    public static void zAddToDictionary(String wordStr, int score) {
        Jedis jedis = JedisDBPool.getConnectJedis();
        jedis.zadd(DICTIONARY_PATH,score, wordStr);
        jedis.close();
    }

    /**
     *
     * @param prefixStr 前缀字符串
     * @param num 获取的词数
     */
    public static Set<String> prefixSearch(String prefixStr, int num) {
        Jedis jedis = JedisDBPool.getConnectJedis();
        // 查询出关键字处于有序集合的位置
        Long wordIndex = jedis.zrank(DICTIONARY_PATH, prefixStr);
        // 3、获取指定起始位置到末尾的所有值
        Set<String> results = jedis.zrange(DICTIONARY_PATH, wordIndex, -1L);
        for (String result: results) {
            if (result.startsWith(prefixStr)) {
                results.add(result); // 这个里面存储了所有以指定关键字开头的词汇。
            }
        }
        return results;
    }

    @Test
    public static void main(String[] args) {
//基本存储测试
//        set("测试key","测试value");
        //通过给key添加冒号可以使数据在Redis Desktop manager中以文件夹的形式分类展示
//        set("User:测试key","测试value");
//        set("UserDAO:UserToken:2", "1775510ccab28b4319ddd74a2e88068e20220330153648298567871");

//搜索提示功能测试
        //把数据库里的单词全都添加到redis缓存中
        List<Word> wordList = WordDAO.ME.listNewWords(100);
        int i = 0;
        for (Word word : wordList) {
            zAddToDictionary(word.getWord_string(), i);
        }
        //查询测试
        Set<String> result = prefixSearch("input", 10);
        System.out.println(result.size());
    }
}
